<template>
  <div class="event-list common-list-container__v2">
    <div ref="tableHeaderContainer" class="filter-wrapper bg-w">
      <form onsubmit="return false;">
        <div class="searh-input-box">
          <!-- 输入框搜索/重置 -->
          <div class="base-search-group input-with-append-search">
            <el-input
              v-model="searchParams.keywords"
              :placeholder="$t('im.list.pla1')"
              class="task-mr12 search-input"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              <el-button
                type="primary"
                slot="append"
                @click="
                  searchParams.pageNum = 1;
                  search();
                "
                native-type="submit"
                v-track="$track.formatParams('KEYWORD_SEARCH')"
              >
                {{$t('common.base.search')}}
              </el-button>
            </el-input>
            <el-button type="ghost" class="reset-btn" @click="resetParams" v-track="$track.formatParams('RESET_SEARCH')"
            >{{$t('common.base.reset')}}</el-button
            >
          </div>
          <!-- 高级搜索 -->
          <div
            class="advanced-search-btn pointer"
            @click.self.stop="panelSearchAdvancedToggle"
          >
            <i class="iconfont icon-filter"></i>
            {{$t('common.base.advancedSearch')}}
          </div>
        </div>
      </form>
      <div v-show="packUp" class="filter-box">
        <usual-state-select
          ref="usualStateSelect"
          :state-list="stateList"
          :choose-res="stateRes"
          @updateRes="updateRes"
        ></usual-state-select>
      </div>
    </div>
    <div class="bbx-normal-pack-up">
      <div @click="changePackUp()">
        <i class="iconfont icon-Icon_up" v-show="packUp"></i>
        <i class="iconfont icon-more" v-show="!packUp"></i>
      </div>
    </div>
    <div class="common-list-view__v2">
      <div ref="tableDoContainer" class="operate-box">
        <div class="operate-box__left">
          <!-- 删除 -->
          <!-- TODO CASE_DELETE editAll 权限 -->
          <el-button class="reset-btn delete-btn" @click="handleDelete" v-track="$track.formatParams('DELETE')">
            <i class="iconfont icon-delete task-icon task-font14"></i>
            {{$t('common.base.delete')}}
          </el-button>
        </div>
        <div class="operate-box__right">
          <!-- 更多操作 -->
          <el-dropdown v-if="isButtonDisplayed && exportIn">
            <div class="cur-point">
              <span>{{$t('common.base.moreOperator')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="isButtonDisplayed && exportIn">
                <div @click="handleExport(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{$t('common.base.export')}}</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="isButtonDisplayed && exportIn">
                <div @click="handleExport(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{$t('common.base.exportAll')}}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <!-- 选择列 -->
          <div class="guide-box">
            <div
              :class="['task-pointer', 'cur-point', 'ml_12']"
              @click="showAdvancedSetting"
              v-track="$track.formatParams('SELECT_COLUMN')"
            >
              <span>{{$t('common.base.choiceCol')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
          </div>
        </div>
      </div>

      <!-- <div
        ref="BaseSelectionBarComponent"
        v-show="multipleSelection.length"
        class="common-list-selection__v2 mt_8"
      >
        已选择
        <span>{{ multipleSelection.length }}</span
        >条
        <span class="pointer" @click="toggleClearSelection">清空</span>
      </div> -->

      <!-- 表格 -->
      <el-table
        v-table-style
        ref="table"
        class="mt_12 bbx-normal-list-box"
        stripe
        :row-key="getRowKey"
        :data="IMPage.list"
        :highlight-current-row="false"
        :border="true"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        @header-dragend="headerDragend"
        v-loading="loading"
        header-row-class-name="common-list-table-header__v2"
        :height="tableContainerHeight"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!loading"></BaseListForNoData>
        </template>
        <el-table-column
          type="selection"
          width="48"
          align="center"
          class-name="select-column"
          :reserve-selection="true"
        ></el-table-column>
        <template v-for="column in columns">
          <el-table-column
            v-if="column && column.show"
            show-overflow-tooltip
            :align="column.align"
            :key="column.field"
            :label="column.displayName"
            :min-width="column.minWidth"
            :prop="column.field"
            :sortable="column.sortable"
            :width="column.width"
            :resizable="true"
            :fixed="column.fixLeft || false"
          >
            <template slot-scope="scope">
              <template v-if="column.renderCell">
                <base-table-cell
                  :render-cell="column.renderCell"
                  :column="column"
                  :row="scope.row"
                ></base-table-cell>
              </template>
            
              <template v-else-if="column.field === 'relationUserId'">
                <template v-if="isOpenData">
                  <open-data
                    type="userName"
                    :openid="scope.row.relationUserStaffId"
                  ></open-data>
                </template>
                <template v-else>
                  {{ scope.row[column.field] }}
                </template>
              </template>
              <template v-else-if="column.field === 'eventNo'">
                <template v-if="scope.row.bizRelInfo">
                  <ItemPopover :width="column.width" :scope="scope" type="eventNo" @popoverClick="popoverClick" />
                </template>
              </template>
              <template v-else-if="column.field === 'solveStatus'">
                <span
                  v-if="scope.row.solveStatus"
                  class="imlist-tag-option"
                  :style="{
                    backgroundColor:
                      solveStatusMap[scope.row.solveStatus].color,
                  }"
                >
                  {{ solveStatusMap[scope.row.solveStatus].text }}
                </span>
              </template>
              <template v-else-if="column.field === 'serviceNumber'">
                {{scope.row.serviceNumber}}
              </template>
              <template v-else-if="column.field === 'bizRelTaskInfo'">
                <template v-if="scope.row.bizRelTaskInfo">
                  <ItemPopover :width="column.width" :scope="scope" type="bizRelTaskInfo" @popoverClick="popoverClick" />
                </template>
              </template>
              <template v-else-if="column.field === 'bizRelProductInfo'">
                <template v-if="scope.row.bizRelProductInfo">
                  <ItemPopover :width="column.width" :scope="scope" type="bizRelProductInfo" @popoverClick="popoverClick" />
                </template>
              </template>
              <template v-else-if="column.field === 'responseDuration'">
                <span>
                  {{scope.row.responseDuration >> 0 | fmt_h_m_s}}
                </span>
              </template>
              <!-- 富文本 -->
              <template v-else-if="column.formType === 'richtext'">
                <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
                  <span v-if="scope.row.attribute && scope.row.attribute[column.field]">{{$t('common.base.view')}}</span>
                </div>
              </template>
              <template v-else-if="column.isSystem === 0">
                {{ $formatFormField(column, scope.row) }}
              </template>
            </template>
          </el-table-column>
        </template>
        <el-table-column
          fixed="right"
          :label="$t('common.base.operation')">
          <template slot-scope="scope">
            <el-button 
              type="text"
              v-if="allowImView"
              v-track="$track.formatParams('TO_DETAIL', null, 'LIST_OPERATION')"
              @click="goDetail(scope.row)">
              {{$t('common.base.detail')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页信息 -->
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-12 pad-b-16 bg-w pad-t-16">
        <div class="list-info" >
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{ IMPage.total || 0 }}</span>
          </i18n>
          <template v-if="multipleSelection&&multipleSelection.length>0">
            <i18n path="common.base.table.selectedNth">
                <span  place="count"
                class="color-primary pad-l-5 pad-r-5"
              >{{ multipleSelection.length }}</span>
            </i18n>
            <span class="color-primary cur-point" @click="toggleClearSelection">{{$t('common.base.clear')}}</span>
          </template>
        </div>
        <el-pagination
          background
          hide-on-single-page
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="IMPage.total"
        >
        </el-pagination>
      </div>

      <!-- 高级搜索框 -->
      <base-search-drawer
        :show.sync="visible"
        :storage-key="advancedColumnNumStorageKey"
        @reset="resetParams"
        @search="advancedSearch"
        @changeWidth="setAdvanceSearchColumn"
        @getColumnNum="setAdvanceSearchColumn"
      >
        <base-search-panel
          ref="searchPanel"
          :column-num="columnNum"
          :fields="advanceSearchColumn"
        />
      </base-search-drawer>

      <!-- 导出工单 -->
      <base-export-group
        ref="exportPanel"
        :alert="exportAlert"
        :columns="exportColumnList"
        :build-params="buildExportParams"
        :group="true"
        :validate="checkExportCount"
        method="post"
        :action="imListExport"
      />

      <!-- 选择列 -->
      <biz-select-column ref="advanced" mode="im" @save="saveColumnStatus" />
    </div>
    <!--查看富文本 -->
    <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform';
import { checkButtonDisplayed, getRootWindow } from '@src/util/dom';
import * as _ from 'lodash';

import * as IMApi from '@src/api/ImApi.js';
import Page from '@model/Page';
import {
  getColumnFields,
  getAdvancedFields,
  getExportSystemInfo,
} from './fields';

import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import BaseTableCell from 'packages/BaseTableCell';
import UsualStateSelect from './components/UsualStateSelect.vue'
import { formatDate } from 'pub-bbx-utils';
import { storageGet, storageSet } from '@src/util/storage';

/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts';
import { SessionSourceMap } from '@model/enum/ImEnum.js'
/* export & import */
import { imListExport } from '@src/api/Export';
// import { eventListImport_1, eventListImportTem_1 } from '@src/api/Import';
import AuthUtil from '@src/util/auth';
import { safeNewDate } from '@src/util/time';

import AuthMixin from '@src/mixins/authMixin';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
const IM_LIST_KEY = 'im_list';
const IM_PAGE_SIZE_KEY = 'im_page_size';
import i18n from '@src/locales'
import { defaultTableData } from '@src/util/table'

/** components */
import ItemPopover from '@src/modules/im/imList/components/ItemPopover.vue'
/* version control mixin */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'

export default {
  name: 'imConversationList',
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [BaseTableCell.name]: BaseTableCell,
    UsualStateSelect,
    ItemPopover,
  },
  mixins: [AuthMixin, VersionControlTaskMixin],
  data() {
    return {
      defaultTableData,
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      searchParams: {
        keywords: '',
        pageSize: 10,
        pageNum: 1,
        orderDetail: {},
        solveStatus:''
      },
      currentEventType: {},
      multipleSelection: [],

      IMPage: new Page(),
      visible: false,
      columns: [],
      columnNum: 1,
      exportColumnList: [],
      AllConsultTypeList:[],
      navWidth: window.innerWidth - 120,
      isFold: false,
      loading: true,
      hasSub: 1,
      advancedColumnNumStorageKey: StorageKeyEnum.IMListAdvancedColumnNum,
      searchParamsAll: {},
      AllPutChannel: [],
      AllServiceNumber:[],
      imListExport,
      solveStatusMap: {
        UNSOLVED: {
          color: '#FF7043',
          text: i18n.t('common.base.notResolved'),
        },
        SOLVED: {
          color: '#00C853',
          text: i18n.t('common.base.resolved'),
        },
      },
      stateList: [
        {
          key: 'hfly',
          label: `${i18n.t('common.fields.imSource.displayName')}：`,
          haveAll: true,
          mulity: false,
          showType: 'select',
          hoverIconClass: 'icon-question color-tips-icon mar-l-10 just-cur-point',
          children: [],
        },
        {
          key: 'jjzt',
          label: `${i18n.t('im.list.stateList.label1')}：`,
          haveAll: true,
          mulity: false,
          showType: 'select',
          hoverIconClass: 'icon-question color-tips-icon mar-l-10 just-cur-point',
          children: [
            { key: 'all', label: i18n.t('common.base.all'), value: '' },
            { key: 'SOLVED', label: i18n.t('common.base.resolved'), value: 'SOLVED' },
            { key: 'UNSOLVED', label: i18n.t('common.base.notResolved'), value: 'UNSOLVED' },
          ],
        },
        {
          key: 'hhzt',
          label: `${i18n.t('im.list.stateList.label2')}：`,
          haveAll: true,
          mulity: false,
          showType: 'select',
          hoverIconClass: 'icon-question color-tips-icon mar-l-10 just-cur-point',
          children: [
            { key: 'all', label: i18n.t('common.base.all'), value: '全部' },
            { key: 0, label: i18n.t('im.list.stateList.label3'), value: '机器人' },
            { key: 1, label: i18n.t('im.list.stateList.label4'), value: '排队中' },
            { key: 2, label: i18n.t('im.list.stateList.label5'), value: '进行中' },
            { key: 3, label: i18n.t('im.list.stateList.label6'), value: '已结束' },
          ],
        },
      ],
      stateRes: {
      },
      auth: {},
      customerFields:[],
      tableContainerHeight:'440px',
      packUp:true
    };
  },
  computed: {
    // 高级搜索字段
    advanceSearchColumn() {
      return [
        ...getAdvancedFields(this, {
          AllPutChannel: this.AllPutChannel,
          AllServiceNumber: this.AllServiceNumber,
          AllConsultTypeList: this.AllConsultTypeList,
        }),
        ...this.customerFields.filter(f => f.isSearch == 1)
      ];
    },

    // 当前选中的工单ids
    selectedIds() {
      return this.multipleSelection.map(p => p.id);
    },

    /** im列表字段 */
    imListFields() {
      const columnFields = [...this.customerFields, ...getColumnFields(this)];

      return []
        .concat(columnFields)
        .filter(f => {
          
          // 关联工单 是否显示
          if (f.fieldName == 'bizRelTaskInfo') {
            return this._isShowTaskModule
          }
          
          return f.formType !== 'separator' && f.formType !== 'info'
        })
        .sort((a, b) => a.orderId - b.orderId);
    },
    exportIn() {
      return AuthUtil.hasAuth(this.auth, 'CASE_CONVERSATION_EXPORT')
    },
    allowImView() {
      return this.globalIsHaveImViewDetailAuth
    },
    // 邮件客服灰度
    isOpenMailIM() {
      return true
    },
  },
  created() {
    this.sethflyChildren()
  },

  async mounted() {
    

    // 获取缓存的pagesize
    const localStorageData = await this.getLocalStorageData();
    const res = await this.getTemplateByTenantId()
    this.customerFields = res
    this.searchParams.pageSize = localStorageData[IM_PAGE_SIZE_KEY] || 10;
    this.initialize(); // 获取初始化数据
    this.search();
    this.getAllPutChannel();
    this.getAllServiceNumber();
    this.getConsultTypeList();
    this.$refs['usualStateSelect'].initChooseRes();
    this.getAuthByRootInitData();
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
        that_.navWidth = window.innerWidth - 120;
      }, 500)
    })
  },
  methods: {
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.attribute?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId, false)
    },
    // 获取window._init auth
    getAuthByRootInitData() {
      const rootWindow = getRootWindow(window)
      const _initData = JSON.parse(rootWindow?._init || '{}')
      this.auth = _initData?.user?.auth || {}
    },
    OpenEvent(item) {
      // this.$platform.openTab({
      //   id: `event_view_${item.bizId}`,
      //   title: `事件${item.bizNo}`,
      //   close: true,
      //   url: `/event/view/${item.bizId}`,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: item.bizId,
        titleKey: item.bizNo,
      })
    },
    // 获取渠道列表
    getAllPutChannel() {
      IMApi.getAllPutChannel().then(res => {
        const { code, message = this.$t('common.base.tip.systemIsError'), data = [] } = res;
        if (code !== 0) return this.$platform.alert(message);
        this.AllPutChannel = data.map(item => {
          item.text = item.channelName;
          item.value = item.id;
          return item;
        });
      });
    },
    // 获取客服编号
    getAllServiceNumber() {
      IMApi.getAllCustomerService().then(res => {
        const { code, message = this.$t('common.base.tip.systemIsError'), data = [] } = res;
        if (code !== 0) return this.$platform.alert(message);
        this.AllServiceNumber = data.map(item => {
          if(item.relationUserName){
            item.text = `${item.customerServiceName} (${item.relationUserName})`;
          }else{
            item.text = `${item.customerServiceName}`;
          }
          item.value = item.customerServiceNumber;
          return item;
        });
      });
    },
    // 获取客服编号
    getConsultTypeList() {
      IMApi.getConsultTypeList().then(res => {
        const { code, message = this.$t('common.base.tip.systemIsError'), data = [] } = res;
        if (code !== 0) return this.$platform.alert(message);
        this.AllConsultTypeList = data.setting.dataSource || [];
      });
    },
    // 获取服务会话列表
    queryConversationList(params = {}) {
      this.loading = true;
      IMApi.queryConversationList(params)
        .then(res => {
          if (res.code == 0) {  
            if(res.data.list){
              res.data.list.map(v=>{
                if(!v.attribute){
                  v.attribute = {}
                }
              })
            }
            this.IMPage = res.data || [];
          }else{
            this.$message.error(res?.message ?? this.$t('common.base.tip.systemIsError'))
          }
        })
        .catch(err => {
          console.error(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 搜索
    search() {
      // 获取高级搜索参数
      let advancedSearchParams = this.$refs.searchPanel
        ? this.$refs.searchPanel.buildParams()
        : {};
      // 处理数据
      if (advancedSearchParams.taskNo) {
        advancedSearchParams.bizList = [
          {
            bizType: 'task',
            taskNo: advancedSearchParams.taskNo,
          },
        ];
      }
      const { customerId = '' } = advancedSearchParams;
      
      const searchParams = {
        ...this.searchParams,
        ...advancedSearchParams,
        customerId,
      };
      this.searchParamsAll = searchParams;
      this.visible = false;

      this.queryConversationList(searchParams);
    },

    // 重置
    resetParams() {
      const fromId = window.frameElement.getAttribute('id');
      this.$platform.refreshTab(fromId);
    },

    // 高级搜索
    panelSearchAdvancedToggle() {
      this.visible = true;
    },

    // 删除
    async handleDelete() {
      const { selectedIds } = this;
      if (!selectedIds.length) {
        this.$platform.alert(this.$t('im.list.tips1'));
        return;
      }

      this.$confirm(this.$t('im.list.tips2'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(async () => {
          const { code } = await IMApi.removeConversations(selectedIds);
          if (code == 0) {
            this.$platform.alert(this.$t('common.base.tip.deleteSuccess'));
            this.toggleClearSelection();
            this.search();
          }
        })
        .catch(() => {});
    },

    /**
     * @description: 导出（全部）
     * @param {Boolean} isExportAll 是否导出全部
     */
    async handleExport(isExportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}im列表数据.xlsx`;
      if (!isExportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(this.$t('common.base.tip.exportUnChooseTip'));
        ids = this.selectedIds;
      }

      const ExportPanelComponent = this.$refs.exportPanel;
      if (!ExportPanelComponent) {
        return console.warn('Caused: $refs.exportPanel is Empty');
      }

      const LocalStorageData = await this.getLocalStorageData();
      let exportCheckedData = LocalStorageData.exportCheckedData;

      if (!exportCheckedData) {
        exportCheckedData = {
          checkedGroup: [],
          checkedMap: {},
          isCheckedAll: false,
          tooltip: true,
        };
      }

      ExportPanelComponent.open(ids, fileName, false, exportCheckedData);
    },

    async initialize(isEventStatus) {
      // Todo接口调用更改
      // 清除导出配置的缓存
      localStorage.removeItem('checkedMap');
      localStorage.removeItem('checkedGroupArr');
      localStorage.removeItem('isCheckedAll');
      this.columns = this.imListFields;
      this.buildColumns(); // 构建表格/选择列字段
      this.buildExportColumns(); // 构建导出字段
    },

    // 构建列表项
    async buildColumns() {
      // 获取缓存在本地的选择列配置
      const localStorageData = await this.getLocalStorageData();
      const columnStatus = localStorageData.columnStatus || [];

      const localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});

      let imListFields = this.imListFields; // 本地默认的表格项字段
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        // 有本地缓存--列表排序
        imListFields = this.buildSortFields(imListFields, localColumns);
      }

      const columns = imListFields.map(col => {
        // 选择列配置 是否勾选（显示）&宽度
        let show = col.show === true;
        let { width } = col;
        let localField = localColumns[col.field]?.field || null;
        let fixLeft = localField?.fixLeft || null;
        if (null != localField) {
          if (localField.width) {
            width = typeof localField.width == 'number'
              ? `${localField.width}px`
              : localField.width;
          }
          show = localField.show !== false;
        } else {
          show = true;
        }

        col.show = show;
        col.width = width;
        col.minWidth = col.width || 150;
        col.type = 'column';
        col['fixLeft'] = fixLeft && 'left'
        return col;
      });

      this.columns = [];
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
      });
    },

    // 选择列排序
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      return fields.concat(unsortedFields);
    },

    // 构建导出项
    buildExportColumns() {
      // im列表信息
      // 系统信息
      const systemInfo = {
        label: this.$t('common.form.fieldGroupName.system'),
        value: 'systemChecked',
        columns: [...getExportSystemInfo()].map(item => {
          item.export = true;
          item.label = item.displayName;
          return item;
        }).filter(item => {
          
          // 是否显示关联工单
          if (item.exportAlias == 'taskNo') {
            return this._isShowTaskModule
          }
          
          return item
        }),
      };
      // 自定义字段
      const attrInfo = {
        label: this.$t('common.form.fieldGroupName.attribute'),
        value: 'attrChecked',
        columns: [...this.customerFields].map(item => {
          item.export = true;
          item.label = item.displayName;
          return item;
        }),
      };
      this.exportColumnList = [systemInfo,attrInfo].filter(item => {
        return item.columns && item.columns.length > 0;
      });
    },

    // 打开选择列
    showAdvancedSetting() {
      this.$refs.advanced.open(this.columns, this.currentEventType);
    },

    /**
     * @description 表头更改
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map(item => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map(item => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },

    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach(col => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },

    // 保存选择列配置
    saveColumnStatus(event) {
      let columns = event.data || [];
      this.columns = [];
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },

    // 保存选择列配置到本地
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },

    /**
     * @description 获取行的key
     * @param {Object} row 行数据
     * @return {String} key
     */
    getRowKey(row = {}) {
      return row.id;
    },

    // 清空选择框
    toggleClearSelection() {
      this.multipleSelection = [];
      this.$refs.table.clearSelection();
    },

    // 表格选择操作
    handleSelection(selection) {
      this.multipleSelection = selection;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },

    // 排序变化
    sortChange(option) {
      const { column, order, prop } = option;
      const sortedField = this.columns.filter(item => item.fieldName === prop)[0] || {};
      if (column === null) {
        this.searchParams.orderDetail = {};
      } else {
        this.searchParams.orderDetail = {
          column: sortedField.sortName,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          type: sortedField.dataType,
          isSystem: sortedField.isSystem,
        };
      }
      this.search();
    },

    // 页码跳转
    jump(pageNum) {
      this.searchParams.pageNum = pageNum;
      this.IMPage.list = [];
      this.search();
    },

    // 页大小改变
    handleSizeChange(pageSize) {
      this.saveDataToStorage(IM_PAGE_SIZE_KEY, pageSize);
      this.searchParams.pageSize = pageSize;
      this.searchParams.pageNum = 1;
      this.search();
    },

    // 设置高级搜索展示列数
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },

    // 构建导出参数
    buildExportParams(checkedMap, ids) {
      const { systemChecked = [],attrChecked = [] } = checkedMap;

      let exportAll = !ids || !ids.length;
      let exportTotal = exportAll ? this.IMPage.total : this.selectedIds.length;
      const exportSearchModel = {
        exportTotal,
        ...this.searchParamsAll,
      };

      let params = {
        dataTotal: exportTotal,
        exportSearchModel: JSON.stringify(exportSearchModel),
      };
      let export_sys = this.exportData([...systemChecked,...attrChecked]);
      params['ids'] = exportAll ? '' : this.selectedIds.join(',');
      params['checked'] = export_sys
        .map(item => {
          return item;
        })
        .join(',');

      return params;
    },

    /**
     * 导出数据
     */
    exportData(list = []) {
      const export_list = this.exportColumnList;
      let xlistColumns = [];
      export_list.forEach((xlist) => {
        xlistColumns = xlistColumns.concat(xlist.columns);
      });

      return xlistColumns
        .map(v => {
          let bool = list.some(item => {
            if (v.exportAlias) {
              return v.exportAlias === item;
            }
            return v.fieldName === item;
          });
          if (bool) {
            return v.exportAlias ? v.exportAlias : v.fieldName;
          }
        })
        .filter(item => {
          return item;
        });
    },

    // 导出提示
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },

    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.IMPage.total > max
        ? this.$t('common.base.tip.exportMostTip')
        : null;
    },

    // 获取本地localstorage
    getLocalStorageData() {
      const dataStr = storageGet(IM_LIST_KEY, '{}');
      return JSON.parse(dataStr);
    },

    // 保存数据到本地localstorage
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(IM_LIST_KEY, JSON.stringify(data));
    },
    updateRes(data, checkData){
      if(checkData && checkData.parent) {
        this.$track.clickStat(this.$track.formatParams('QUICK_SEARCH', checkData.parent.label));
      }
      this.stateRes = data
      let solveStatus = data.jjzt[0]
      let conversationStatus = data.hhzt[0]
      let source = data.hfly[0]
      if(solveStatus == 'all'){
        solveStatus = ''
      }
      if(conversationStatus == 'all'){
        conversationStatus = ''
      }
      if(source == 'all'){
        source = ''
      }
      this.searchParams.solveStatus = solveStatus
      this.searchParams.conversationStatus = conversationStatus
      this.searchParams.source = source
      this.search()
    },
    goDetail(obj){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `im_view_${obj.id}`,
      //   title: `会话详情${obj.conversationNumber}`,
      //   close: true,
      //   url: `/im/imDetail?id=${obj.id}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageImView,
        key: obj.id,
        titleKey: obj.conversationNumber,
        params: `id=${obj.id}`,
        fromId
      })
    },
    // 获取用户自定义模板
    async getTemplateByTenantId() {
      let fields = []
      await IMApi.getTemplateByTenantId().then(res => {
        if (res.code === 0) {
          res.data.map(v=>{
            v.isSystem = 0
            v.tableName = 'im'
            v.minWidth = 150
            v.dataType = v.formType
            v.field = v.fieldName
            // 筛选出四个系统字段
            if(['serviceNumber', 'consultName', 'solveStatus', 'serviceRemark'].includes(v.fieldName)){
              v.isSystem = 1
            }
          });
          // 过滤掉重复字段,系统字段，不需要显示的自定义字段
          fields = res.data.filter(v=>v.fieldName != 'serviceNumber')
            .filter(v=> v.fieldName != 'consultName')
            .filter(v=> v.fieldName != 'serviceRemark')
            .filter(v=> v.fieldName != 'solveStatus')
            .filter(v=> v.formType != 'autograph')
            .filter(v=> v.formType != 'attachment')
            .filter(v=> v.formType != 'info')
            .filter(v=> v.formType != 'separator')
        }
      });
      return fields
    },
    openDetail(taskId, taskNo){
      let fromId = window.frameElement.getAttribute('id');

      // this.$platform.openTab({
      //   id: `frame_tab_taskView_${taskId}`,
      //   url:`/task/view/${taskId}`,
      //   title: `工单${taskNo}`,
      //   close: true,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        titleKey: taskNo,
        fromId
      })
    },
    // 跳转到产品详情
    toProductDetail(productId){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `product_view_${productId}`,
      //   title: '产品详情',
      //   close: true,
      //   url: `/customer/product/view/${productId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductView,
        key: productId,
        params: 'noHistory=1',
        fromId
      })
    },
    advancedSearch(){
      this.searchParams.pageNum = 1
      this.search()
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 8 - 32;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        // console.log(pxArray, 'pxArray')
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    popoverClick(type,item){
      if (type === 'eventNo') return this.OpenEvent(item)
      if (type === 'bizRelTaskInfo') return this.openDetail(item.bizId, item.bizNo)
      if (type === 'bizRelProductInfo') return this.toProductDetail(item.bizId)
    },
    sethflyChildren() {
      const list = [
        { key: 'all', label: i18n.t('common.base.all'), value: '' },
        { key: 'im', label: SessionSourceMap['im'], value: 'im' },
        { key: 'weChat', label: SessionSourceMap['weChat'], value: 'weChat' },
      ];
      if (this.isOpenMailIM) {
        list.push({ key: 'emailService', label: SessionSourceMap['emailService'], value: 'emailService' })
      }
      const index = this.stateList.findIndex(v=> v.key == 'hfly')
      this.$set(this.stateList[index],'children',list)
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-table__body .el-table__row td .cell,
.el-table__header thead tr th .cell {
  min-height: 40px;
  height: auto;
}
.OpenLink {
  color: $color-primary-light-6;
  cursor: pointer;
  height: 20px;
  margin-bottom: 5px;
  &:last-child{
    margin-bottom: 0;
  }
}
.OpenLink:hover {
  text-decoration: underline;
}
.event-list {
  .search-input {
    width: 440px;
  }

  > div {
    border-radius: 4px;
  }

  .filter-wrapper {
    .searh-input-box {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 16px;
      // border-bottom: 1px solid #f2f2f2;
      .advanced-search-btn {
        @include fontColor;
      }
      .base-search-group {
        margin-right: 24px;
      }
    }
    .filter-tab {
      &__item {
        display: flex;
        flex-wrap: wrap;
        line-height: 32px;
        border-bottom: 1px solid #f2f2f2;
        &:last-child {
          border-bottom: 0;
        }
      }
      &__label {
        background: #f5f5f5;
        width: 108px;
        text-align: center;
        color: #666;
      }
      &__content {
        position: relative;
        display: flex;
        flex-wrap: wrap;
        flex: 1;
        height: auto;
        .content-item {
          display: inline-block;
          width: 130px;
          overflow: hidden;
          padding-left: 10px;
          cursor: pointer;
          white-space: nowrap;
          text-overflow: ellipsis;
          color: grey;
          &:hover {
            color: #333;
          }
          .content-item-label.actived {
            color: $color-primary-light-6 !important;
          }
        }
        .fold-btn {
          position: absolute;
          right: 10px;
        }
      }
      &__content.fold {
        height: 30px;
        overflow: hidden;
      }
    }
    .filter-box{
      padding: 0 16px 16px;
    }
  }

  .common-list-view__v2 {
    padding-bottom:0;
    .operate-box {
      .cur-point {
        color: #595959;
      }
      display: flex;
      justify-content: space-between;
      align-items: center;
      > div {
        display: flex;
        align-items: center;
        .icon-dingyuetongzhiguanli {
          font-size: 14px;
          &.actived {
            color: $color-primary-light-6;
          }
        }
      }
    }
  }
}
.reset-btn {
  background: #f5f8fa;
}
.delete-btn {
  padding-right: 16px !important;
}
.import-event {
  position: relative;
  left: -15px;
  padding-left: 15px;

  &:hover &-item {
    display: block;
  }

  &-item,
  .import-event-item-children {
    position: absolute;
    background: #fff;
    color: #333;
    left: -115px;
    top: -1px;
    border: 1px solid #eee;
    border-radius: 4px;
    display: none;

    > div {
      padding: 4px 15px;
      width: 120px;
      position: relative;

      &:hover {
        background-color: $color-primary-light-1;
        color: $color-primary-light-6;
      }
    }
  }

  &-item {
    top: -7px;
    > div:hover {
      .import-event-item-children {
        display: block;
      }
    }
  }
}
</style>
<style lang="scss">
.wx-im {
  color: $color-main;
  font-size: 10px;
}
.imlist-tag-option {
  display: inline-block;
  border-radius: 12px;
  line-height: normal;
  padding: 2px 8px;
  color: #ffffff;
  text-align: center;
}
</style>
